package com.huazi.msmservice.controller;

import com.huazi.commonutils.CommentResult;
import com.huazi.msmservice.sevice.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * @create 2021-03-27 11:53
 */
@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //发送短信方法
    @GetMapping("send/{phone}")
    public CommentResult sendMsm(@PathVariable("phone") String phone){

        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get("code");
        if(!StringUtils.isEmpty(code)){
            return CommentResult.getOK();
        }
        //2 如果获取不到，就设置code

        //生成随机数验证码
        String codeNew = getSendNumber();
        Map<String,Object> param=new ConcurrentHashMap<>();
        param.put("code",codeNew);
        boolean b = msmService.sendMsm(param, phone);
        //如果发送短信成功，则缓存验证码
        if(b) {
            redisTemplate.opsForValue().set(phone,codeNew,5, TimeUnit.MINUTES);//分钟单位

            return CommentResult.getOK();
        }
        return CommentResult.getError().data("message","短信发送失败");
    }
    //生成随机字符串方法
    public String getSendNumber(){
        int substring = new Random().nextInt(1000000);
        return String.valueOf(substring);
    }
}
